<template>
  <div class="container" ref="mainCon">
    <topTitle :titleText="titleText" :titleExplain="titleExplain"></topTitle>
    <div class="mainCon">
      <el-form
        :inline="true"
        :model="filterField"
        ref="searchConditions"
        label-position="left"
        label-width="86px"
      >
        <el-row
          class="toolbar searchInputWidth"
          style="padding-bottom: 0; margin-left: 0 !important"
        >
          <el-form-item label="选择区域：" class="row-padding-bottom">
            <el-cascader
              ref="manageArea"
              v-model="areaId"
              :options="areasOptions"
              @change="getAreaId"
              clearable
              filterable
              :props="{ checkStrictly: true }"
            ></el-cascader>
          </el-form-item>
          <el-form-item style="margin-left: 16px">
            <el-button
              type="primary"
              class="saveBtn commonBut"
              @click="beginSetting"
              >配置</el-button
            >
          </el-form-item>
          <br />
        </el-row>
        <!-- <div class="spacing"></div> -->
        <!-- <div ref="tableBox" class="tableBoxCur"> -->
        <el-table
          :data="tableList"
          v-if="tableList.length"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          highlight-current-row
          v-loading="loading"
          stripe
          style="border: 1px solid #dfe6ec; border-bottom: 0"
        >
          <el-table-column
            prop="rn"
            label="序号"
            align="center"
            :formatter="formatTd"
          ></el-table-column>
          <el-table-column
            prop="name"
            label="等级"
            align="center"
            :formatter="formatTd"
          ></el-table-column>
          <el-table-column
            prop="levelTypeDesc"
            label="配置类型"
            align="center"
            :formatter="formatTd"
          ></el-table-column>
          <el-table-column
            prop="value"
            label="减免比例"
            align="center"
            :formatter="formatTd"
          >
            <template slot-scope="scope">
              <span v-if="scope.row.levelType == 'REDUCTION'">{{
                scope.row.value + '%'
              }}</span>
              <span v-else>{{ scope.row.value + '天' }}</span>
            </template>
          </el-table-column>

          <!-- 表格数据为空时，页面显示 -->
          <div slot="empty" v-show="isShow">
            <emptyTable emptyText="暂无相关信息"></emptyTable>
          </div>
        </el-table>
        <!-- </div> -->
        <div style="margin-top: 16px; padding: 20px; border: 1px solid #dcdfe6">
          <div class="secondaryTitle secondaryTitleTheme">区域配置开关</div>
          <el-form-item
            label="区域配置开关："
            label-width="120px"
            style="margin: 0; margin-top: 10px; padding-left: 16px"
            class="row-padding-bottom"
          >
            <el-switch
              v-sdc
              v-model="filterField.configSwitch"
              @change="changeConfig"
              active-value="1"
              inactive-value="0"
            ></el-switch>
          </el-form-item>
        </div>
      </el-form>
      <!-- <Pagination ref="pagination" :filterField="filterField" :requestUrl="requestUrl"></Pagination> -->
      <div class="uploadFiles">
        <p class="secondaryTitle secondaryTitleTheme">保证金政策文件</p>
        <div class="uploadBox">
          <!-- <el-button class="commonBut saveBtn" icon="icon iconfont iconshangchuan">
                        <span class="opetareText">上传附件</span>
                    </el-button> -->
          <el-button
            class="uploadImg"
            icon="icon iconfont iconshangchuan"
            @click="$refs.uploadFileInput.click()"
          >
            &nbsp;上传</el-button
          >
          <slot name="templatePreview"></slot>
          <span class="uploadImgState">
            <span
              >支持上传word或pdf格式的文件，单个大小限制5M内，最多5个文件</span
            >
          </span>
          <div class="upLoadDom">
            <form id="uploadFileForm">
              <input
                type="file"
                id="uploadFileInput"
                ref="uploadFileInput"
                name="file"
                @change="fileChange"
              />
            </form>
          </div>
        </div>
        <ul class="upLoadFile">
          <li v-for="(item, index) of oldSrcList" :key="index">
            <i class="el-icon-document links"></i>
            <span class="names">
              {{ item.name }}
            </span>
            <span class="linksBox">
              <el-link type="primary" :href="item.url" target="_blank"
                >查看</el-link
              >
              <el-link type="primary" class="del" @click="delFile(item)"
                >删除</el-link
              >
            </span>
          </li>
        </ul>
      </div>
    </div>
    <!-- 配置弹窗 -->
    <el-dialog
      title="保证金配置"
      :visible.sync="showDialog"
      :close-on-click-modal="false"
      @close="closeDialog()"
      custom-class="dialog-minwidth"
      width="640px"
      :modal-append-to-body="false"
    >
      <el-row class="settingItems">
        <el-col span="7">信用等级</el-col>
        <el-col span="7">配置类型</el-col>
        <el-col span="7">减免比例/缓缴天数</el-col>
      </el-row>
      <el-form ref="dataFormLXR" :model="formData">
        <el-row
          class="settingItems"
          v-for="(item, index) in formData.settingList"
          :key="index"
        >
          <el-col span="7">
            <el-form-item
              :prop="'settingList.' + index + '.name'"
              :rules="[
                {
                  required: true,
                  message: '请选择信用等级',
                  trigger: ['change'],
                },
              ]"
            >
              <el-select v-model="item.name" style="width: 100%">
                <el-option
                  :disabled="item.disabled"
                  v-for="item in userfulLevel"
                  :key="item.id"
                  :label="item.gradeLevel"
                  :value="item.gradeLevel"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col span="7">
            <el-form-item>
              <el-radio-group v-model="item.levelType">
                <el-radio label="REDUCTION">减免</el-radio>
                <el-radio label="WAIT_PAY">缓缴</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col span="7" v-if="item.levelType == 'REDUCTION'">
            <el-form-item
              :prop="'settingList.' + index + '.value'"
              :rules="rules.value"
            >
              <el-input
                v-model="item.value"
                style="width: calc(100% - 20px)"
              ></el-input>
              <span style="display: inline-block">{{
                item.levelType == 'REDUCTION' ? '%' : '天'
              }}</span>
            </el-form-item>
          </el-col>
          <el-col span="7" v-else>
            <el-form-item
              :prop="'settingList.' + index + '.value'"
              :rules="[
                {
                  required: true,
                  pattern: /(^[1-9]\d*$)/,
                  message: '请输入缓缴天数',
                  trigger: 'blur',
                },
              ]"
            >
              <el-input v-model="item.value" style="width: 110px"></el-input>
              <span style="width: 30px; display: inline-block">{{
                item.levelType == 'REDUCTION' ? '%' : '天'
              }}</span>
            </el-form-item>
          </el-col>
          <el-col span="3"
            ><el-link type="danger" @click="deleteItem(index, item)"
              >删除</el-link
            ></el-col
          >
        </el-row>
      </el-form>

      <!-- <el-button class="addSetting" @click="addSetting"><i class="el-icon-plus"></i> 添加配置</el-button> -->
      <el-row @click.native="addSetting" class="addLevel">
        <span style="font-size: 25px">+</span>
        <span style="position: relative; top: -4px">添加配置</span>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="closeDialog()" class="cancel"
          >取 消</el-button
        >
        <el-button
          type="primary"
          class="save"
          @click.native="saveRole()"
          :loading="isSaveLoading"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { mapState, mapActions } from 'vuex'
import common from '@/kits/common.js'
export default {
  name: 'bondSetting',
  data() {
    var checkPresent = (rule, value, callback) => {
      let obj = this.formData.settingList[this.formData.settingList.length - 1]
      if (obj.levelType == 'REDUCTION') {
        var reg = /^[\+]?(([1-9]\d*)|\d)$/
        if (!reg.test(value)) {
          return callback(new Error('请输入正整数或0'))
        } else {
          if (value > 100) {
            return callback(new Error('请输入0-100之间的整数'))
          } else {
            callback()
          }
        }
      } else {
        if (!value) {
          callback(new Error('请输入缓缴天数'))
        } else if (!/(^[1-9]\d*$)/.test(value)) {
          callback(new Error('请输入正整数'))
        } else {
          callback()
        }
      }
    }
    return {
      titleText: '保证金减免配置',
      tableList: [],
      id: '',
      areaId: '', //区域
      filterField: {
        areaId: '42', //区域
        configSwitch: '0',
      },

      oldSrcList: [],
      srcList: [],
      showDialog: false,
      isSaveLoading: false,
      formData: {
        settingList: [],
      },
      rules: {
        value: [{ required: true, validator: checkPresent, trigger: ['blur'] }],
      },
      ruleItems: {},
      levelList: [],
    }
  },

  mounted() {
    this.filterField.areaId = this.$store.state.areaInfoArr.areaId
    this.areaId = this.filterField.areaId
    this.load()
    this.getAreas({ areaId: this.filterField.areaId })
    this.getLevelConfig()
    this.getFileList()
  },
  computed: {
    ...mapState(['areasOptions']),
    userfulLevel() {
      let arr = this.formData.settingList
      let curArr = this.levelList
      curArr.forEach((item) => {
        item.disabled = false
        if (arr.length) {
          arr.forEach((items) => {
            if (items.name == item.gradeLevel) {
              item.disabled = true
            }
          })
        }
      })
      return curArr
    },
  },
  methods: {
    ...mapActions(['getAreas']),
    // 等级下拉框
    async getLevelConfig() {
      const result = await this.axios.post(
        'api-d/depositpayconfig/expand/projectLevelConfig'
      )
      if (!result.data.hasError) {
        this.levelList = result.data.result
      }
    },
    load() {
      this.axios
        .post('api-d/depositpayconfig/expand/list', {
          areaId: this.filterField.areaId,
        })
        .then((res) => {
          if (!res.hasError) {
            this.filterField.configSwitch = res.data.result.configSwitch + ''
            this.tableList = JSON.parse(
              JSON.stringify(res.data.result.levelList)
            )
              ? JSON.parse(JSON.stringify(res.data.result.levelList))
              : []
            this.id = res.data.result.id
            this.$set(
              this.formData,
              'settingList',
              res.data.result.levelList ? res.data.result.levelList : []
            )
          }
        })
    },
    //区域配置开关
    changeConfig(val) {
      this.axios
        .post('api-d/depositpayconfig/expand/updateSwitch', {
          status: val,
          id: this.id,
        })
        .then((res) => {
          if (!res.data.hasError) {
            this.$message.success(res.data.msg)
            this.load()
          } else {
            this.$message.warning(res.data.errorMsg)
            this.filterField.configSwitch = val ? 0 : 1
          }
        })
    },
    //获取选中的区域最后一级id
    getAreaId() {
      var areaId = this.areaId[this.areaId.length - 1]
      this.filterField.areaId = areaId
      this.load()
      this.getFileList()
    },
    beginSetting() {
      this.showDialog = true
      this.load()
    },
    closeDialog() {
      this.showDialog = false
      this.$set(this.formData, 'settingList', [])
    },
    saveRole() {
      this.$refs['dataFormLXR'].validate((valid) => {
        if (valid) {
          //写保存的逻辑
          this.isSaveLoading = true
          let arr = this.formData.settingList
          if (this.tableList.length) {
            arr.forEach((item) => {
              this.tableList.forEach((datas) => {
                if (item.id == datas.id && item.name != datas.name) {
                  delete item.id
                }
                if (item.name == datas.name) {
                  item.id = datas.id
                }
              })
            })
          }

          let params = {
            areaId: this.filterField.areaId,
            configSwitch: this.filterField.configSwitch,
            levelList: arr,
          }
          this.axios
            .post('api-d/depositpayconfig/expand/addOrUpdateConfig', params, {
              headers: { 'Content-Type': 'application/json' },
            })
            .then((res) => {
              if (!res.data.hasError) {
                this.$message.success('配置成功')
                this.showDialog = false
                this.load()
              } else {
                this.$message.warning(res.data.errorMsg)
              }
              this.isSaveLoading = false
            })
        } else {
          //提示必填信息
        }
      })
    },
    //添加减免规则
    addSetting() {
      let params = {
        name: '',
        levelType: 'REDUCTION',
        value: '',
        areaId: this.filterField.areaId,
      }
      if (!this.formData.settingList.length) {
        this.formData.settingList.push(params)
      } else {
        this.$refs['dataFormLXR'].validate((valid) => {
          if (valid) {
            this.formData.settingList.push(params)
          } else {
            //提示必填信息
          }
        })
      }
    },
    //删除减免规则 id
    deleteItem(index, item) {
      if (item.id) {
        this.$confirm('确定删除该条保证金减免配置?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            this.axios
              .post('api-d/depositpayconfig/expand/deleteConfig', {
                id: item.id,
              })
              .then((res) => {
                if (!res.data.hasError) {
                  this.$message.success('删除成功')
                  this.load()
                } else {
                  this.$message.warning(res.data.errorMsg)
                }
              })
          })
          .catch(() => {})
      } else {
        let arr = this.formData.settingList
        arr.splice(index, 1)
        this.$set(this.formData, 'settingList', arr)
      }
    },
    //获取附件
    getFileList() {
      this.axios
        .post('api-d/depositpayconfig/expand/findFile', {
          areaId: this.filterField.areaId,
        })
        .then((res) => {
          console.log(res)
          if (!res.data.hasError) {
            this.oldSrcList = res.data.result
            this.srcList = res.data.result
          }
        })
    },
    //上传附件
    fileChange(e) {
      var Filedata
      var file
      var fileSize
      let refName = 'uploadFileInput'
      let uploadForm = 'uploadFileForm'
      Filedata = this.$refs[refName].value
      if (!Filedata) {
        return
      }
      try {
        file = this.$refs[refName].files[0]
        fileSize = (file.size / 1024).toFixed(0)
      } catch (e) {
        this.$message({
          message:
            '您的浏览器暂不支持计算上传文件的大小，确保上传文件不要超过5M，建议使用FireFox、Chrome或IE10以上浏览器。',
          type: 'warning',
        })
      }
      // 文件大小和限制类型可以通过子组件传值区分，若不适应于使用页面，可自行判断

      if (this.oldSrcList.length >= 5) {
        this.$message({
          message: `最多上传5个附件`,
          type: 'warning',
        })
        this.$refs[refName].value = ''
        return
      }
      if (fileSize / 1 > 1024 * 5) {
        this.$message({
          message: `最多能上传5M以内的文件`,
          type: 'warning',
        })
        this.$refs[refName].value = ''
        return
      }

      if (!/\.(doc|docx|pdf)$/.test(Filedata)) {
        this.$message({
          message: `仅支持上传doc、docx、pdf格式文件`,
          type: 'warning',
        })
        this.$refs[refName].value = ''
        return
      }

      let that = this
      var options = {
        url: common.uploadUrl + 'api-f/files/upload',
        type: 'POST',
        headers: {
          Authorization: 'Bearer ' + localStorage.getItem('access_token'),
        },
        dataType: 'json',
        success: function (data) {
          e.target.value = ''
          that.saveUploadFile(data)
          // this.$refs[refName].value = ''
          return
        },
        error: function () {},
      }
      $('#' + uploadForm).ajaxSubmit(options)
      return false
    },
    saveUploadFile(item) {
      this.axios
        .post('api-d/depositpayconfig/expand/saveFile', {
          id: this.id,
          file: JSON.stringify([item]),
        })
        .then((res) => {
          if (!res.data.hasError) {
            this.$message({
              message: `上传成功`,
              type: 'success',
            })
            this.getFileList()
          }
        })
    },
    /**
     * @description: 删除上传的附件
     */
    delFile(item) {
      this.$confirm('确定删除该保证金附件吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          // 获取数据
          let params = { ids: item.id }
          this.axios.post('api-f/files/deletelist', params).then((res) => {
            if (!res.data.hasError) {
              this.$message.success('删除成功')
              this.getFileList()
            } else {
              this.$message.warning(res.data.errorMsg)
            }
          })
        })
        .catch(() => {})
    },
  },
}
</script>
<style lang="less" scoped>
.mainCon {
  top: 210px;
  padding: 24px;
}
.settingItems {
  margin-bottom: 22px;
  .el-col {
    height: 36px;
    line-height: 36px;
    text-align: center;
  }
}
.addSetting {
  width: 100%;
  height: 36px;
  line-height: 36px;
  border: 1px dashed #dcdfe6;
  padding: 0;
}
/deep/.el-form-item__error {
  right: 0;
  text-align: center;
}
.uploadFiles {
  margin-top: 16px;
  padding: 20px;
  border: 1px solid #dcdfe6;
  .title {
    line-height: 44px;
    color: #666;
  }
}
.upLoadFile {
  margin-top: 10px;
  max-width: 780px;
  padding-left: 18px;
  li {
    line-height: 26px;
    display: inline-block;
    width: 350px;
    margin-right: 20px;

    font-size: 14px;
    padding: 0 6px;
    &:hover {
      background-color: #f5f7fa;
    }
    .links {
      color: #909399;
      display: inline-block;
      vertical-align: middle;
      font-size: 14px;
      margin-left: 10px;
    }
    .names {
      width: 200px !important;
      display: inline-block;
      height: 26px;
      vertical-align: middle;
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;
      color: #666;
      margin-right: 0 7px 0 5px;
      color: #606266 !important;
      /deep/ .el-link.el-link--primary {
        color: #606266 !important;
        &:hover {
          color: #409eff !important;
        }
        .el-link--inner {
          width: 270px;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }
      }
    }
    .linksBox {
      display: inline-block;
      width: 100px;
      text-align: right;
      .el-link {
        margin-left: 15px;
      }
    }
  }
}
// 上传文件
.uploadBox {
  position: relative;
  padding-left: 18px;
  margin-top: 20px;
  .uploadImg {
    width: 96px;
    height: 36px;
    color: #009588;
    border: 1px solid #009588;
    line-height: 10px;
  }
  .uploadImgState {
    display: block;
    font-size: 14px;
    line-height: 14px;
    color: #999999;
    margin-top: 10px;
  }
  .upLoadDom {
    position: absolute;
    top: 0;
    left: 16px;
    opacity: 0;
    display: none;
    input {
      width: 96px;
      height: 38px;
      cursor: pointer;
    }
  }
  .customBtn {
    width: 120px;
  }
}
// .uploadImg {
//     width: 96px;
//     height: 36px;
//     color: #009588;
//     border: 1px solid #009588;
//     line-height: 10px;
//   }
/deep/.el-input {
  width: 100%;
  height: 36px;
  input {
    text-align: center;
  }
}
</style>
